﻿using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using SCZS.Example.Common;
using SCZS.Example.Common.Options;
using SCZS.Example.Core.ConsulExtend;
using SCZS.Example.Core.RedisExtend;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SCZS.Example.Core.ServiceExtensions
{
    /// <summary>
    /// Redis缓存 启动服务
    /// </summary>
    public static class RedisCacheSetup
    {
        public static void AddRedisCacheSetup(this IServiceCollection services, IConfiguration configuration)
        {
            if (services == null) throw new ArgumentNullException(nameof(services));

            services.AddTransient<IRedisBasketRepository, RedisBasketRepository>();
            

            // 配置启动Redis服务，虽然可能影响项目启动速度，但是不能在运行的时候报错，所以是合理的
            services.AddSingleton<ConnectionMultiplexer>(sp =>
            {
                //获取连接字符串
                RedisConnOptions redisConnOptions = new RedisConnOptions();
                configuration.Bind("", redisConnOptions);

                var configurationOptions = new ConfigurationOptions();
                configurationOptions.TieBreaker = "";
                configurationOptions.CommandMap = CommandMap.Default;
                configurationOptions.DefaultVersion = new Version(2, 0);
                configurationOptions.Password = redisConnOptions.Pwd;
                //configurationOptions.ServiceName = "redis1-master";
                configurationOptions.AbortOnConnectFail = false;
                configurationOptions.Ssl = false;
                configurationOptions.AllowAdmin = true;
                string[] array = redisConnOptions.ConnConfig.Split(',');
                configurationOptions.ResolveDns = true;
                return ConnectionMultiplexer.Connect(configurationOptions);
            });

        }
    }
}
